﻿using System.Text.Json.Serialization;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Menus.Caching;
using Core.Identity.Menus.Dtos;
using Core.Interfaces.Users;
using Core.Models;
using Mapster;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Menus.Features.Queries.GetMe;

/// <summary>
/// 用户菜单
/// </summary>
public class GetMeMenusQuery : IRequest<Result<IEnumerable<MenuDto>>>
{
    /// <summary>
    /// 登录者
    /// </summary>
    public Guid UserId { get; set; }

    /// <summary>
    /// 缓存键
    /// </summary>
    [JsonIgnore]
    public string CacheKey => MenusCacheKey.GetMeMenusCacheKey(UserId.ToString());
    /// <summary>
    /// 缓存选项
    /// </summary>
    [JsonIgnore]
    public IEnumerable<string>? Tags => MenusCacheKey.Tags;
}

public class GetMeMenusQueryQueryHandler(
    IIdentityDbContext context,
    ICurrentUserService currentUserService) : IRequestHandler<GetMeMenusQuery, Result<IEnumerable<MenuDto>>>
{

    public async Task<Result<IEnumerable<MenuDto>>> Handle(GetMeMenusQuery request, CancellationToken cancellationToken)
    {
        if (currentUserService.IsSuperAdmin)
        {
            var menus = await context.Permissions
                .Where(p => p.ShowLink == true && p.MenuType != 3)
                .ToListAsync();

            return await Result<IEnumerable<MenuDto>>
                 .SucceedAsync(menus.Adapt<IEnumerable<MenuDto>>());
        }
        else
        {
            var menus = await context.UserRoles
                .Where(ur => ur.UserId == request.UserId)
                .Select(ur => ur.Role)
                .SelectMany(role => role!.Permissions)
                .Select(s => s.Permission)
                .Distinct()
                .Where(p => p.ShowLink == true && p.MenuType != 3)
                .ToListAsync();

            return await Result<IEnumerable<MenuDto>>
                 .SucceedAsync(menus.Adapt<IEnumerable<MenuDto>>());
        }
    }
}
